<?php

require_once 'functions.php';

class Dispatcher{

	private $default_controller			= "home";
	private $default_controller_method	= "index";

	public $URL;
	
	private $error_messages = array(
		404	=> "%s %s not found."
	);

	public function __construct(){
		global $_dispatcher;
		$this->parseURL();
		$_dispatcher = $this->URL;
	}
	
	public function make(){
		$controller = $this->URL["CONTROLLER"];
		$method = $this->URL["METHOD"];
		$params = $this->URL["PARAMETERS"];
	
		$path_controller = "controllers/".strtolower($controller).".controller.php";
		if(!file_exists($path_controller)){
			$this->error(404,"controller",$controller);
		}
		
		require_once $path_controller;
		$class_controller = strtotitle($controller)."Controller";
		
		$obj = new $class_controller;
		if(!method_exists($obj,$method)){
			$method = "index";
		}
		
		$params_str = array();
		foreach ($params as $param) {
			if (!preg_match('/^\d+$/',$param)) {
				$param = "'".$param."'";
			}
			$params_str[] = $param;
		}
		$toeval = '$ret = $obj->'.$method.'('.implode(",",$params_str).');';
		
		@eval($toeval);
	}
	
	//------------ URL -------------------------
	
	private function parseURL(){
		$this->URL["REQUEST"] = $_REQUEST;
		
		$items = explode("/",$this->URL["REQUEST"]["url"]);
		
		$this->URL["CONTROLLER"] = array_shift($items); isempty($this->URL["CONTROLLER"],$this->default_controller);
		$this->URL["METHOD"] = array_shift($items); isempty($this->URL["METHOD"],$this->default_controller_method);
		$this->URL["PARAMETERS"] = $items;
		
		$path_controller = "controllers/".strtolower($this->URL["CONTROLLER"]).".controller.php";
		if(!file_exists($path_controller)){
			$this->URL["CONTROLLER"] = $this->default_controller;
		}
	}
	
	public function getURL(){
		return $this->URL;
	}
	
	//------------ ERRORS ------------------------
	public function error($errno,$mode,$value){
		$message = sprintf($this->error_messages[$errno],$mode,$value);
		ob_start();
		header("HTTP/1.1 $errno $message");
		header("Status: 404 Not found");
		die("$message");
	}

}

?>